package com.yunfei.yunhetong.upload;

import com.google.gson.Gson;
import com.yunfei.api.v1.magerIndcInfo.contants.MagerIndcInfoContant;
import com.yunfei.api.v1.magerIndcInfo.param.TemplateManagerParam;
import com.yunfei.api.v1.magerIndcInfo.service.MagerIndcInfoService;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.contants.ApplicationConstant;
import com.yunfei.enums.ResultStatus;
import com.yunfei.mapper.aiiidb.MagerIndcInfoTemplateMapper;
import com.yunfei.utils.DateUtil;
import com.yunfei.utils.http.HttpIOUtil;
import com.yunfei.utils.id.IdUtils;
import com.yunfei.utils.string.StringUtil;
import com.yunfei.yunhetong.upload.bo.YunHeTongUploadResult;
import com.yunfei.yunhetong.upload.result.YunHeTongUploadImageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2016/10/20.
 */
@Controller
public class UploadFileController {
    @Autowired
    private Environment env;
    @Autowired
    private MagerIndcInfoService magerIndcInfoService;
    /**
    * @Description: 单文件上传
    * @Param: [file]
    * @return: Msg
    * @Author: zhengyunfei
    * @Date: 2019/7/31
    * @time:16:32
    */
    @PostMapping("/api/upload/one")
    @ResponseBody
    public Object UploadImage(@RequestParam(value = "file", required = false) MultipartFile file,String operatorId, String type,String caCustId,String token,String crmMagerId){
        ResultModel resultModel=new ResultModel();
        if(file == null){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }else{
            String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
            String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
            TemplateManagerParam result = writeFile(file, uploadPath, imageDomain);
            TemplateManagerParam param=new TemplateManagerParam();
            //获取前端传递过来的参数
            param.setOperatorId(operatorId);
            param.setType(type);
            param.setCaCustId(caCustId);
           //本地上传完成，再调用云合同上传接口
            System.out.println("token===="+token);
            HttpIOUtil httpReuqest = new HttpIOUtil();
            String uploadResult="";
            Gson gson=new Gson();
            if(MagerIndcInfoContant.TEMPLATE_TYPE_E1.equals(type)||MagerIndcInfoContant.TEMPLATE_TYPE_H1.equals(type)){
                //合同模板，作废协议模板
                 uploadResult=httpReuqest.uploadFileToYunHeTong(token,result.getLocalPath(),result.getOriFileName().replace(".docx",""));
                YunHeTongUploadResult yunHeTongUploadResult=gson.fromJson(uploadResult, YunHeTongUploadResult.class);
                if(yunHeTongUploadResult.getCode()!=200){
                    resultModel.setCode(yunHeTongUploadResult.getCode());
                    resultModel.setMessage(yunHeTongUploadResult.getMsg());
                }else{
                    String templateId=yunHeTongUploadResult.getData().getTemplateId();
                    param.setFileId(templateId);
                    param.setCrmMagerId(crmMagerId);
                    if(MagerIndcInfoContant.TEMPLATE_TYPE_H1.equals(type)){
                        magerIndcInfoService.add(param);
                    }
                    result.setFileId(templateId);
                    result.setCrmMagerId(crmMagerId);
                    result.setCaCustId(caCustId);
                    resultModel.setData(result);//返回上传成功后的访问路径
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                }
            }
            if(MagerIndcInfoContant.TEMPLATE_TYPE_F1.equals(type)||MagerIndcInfoContant.TEMPLATE_TYPE_G1.equals(type)){
                //管理人公章，法定代表人章
                uploadResult=httpReuqest.uploadImageToYunHeTong(token,result.getLocalPath(),caCustId);
                YunHeTongUploadImageResult yunHeTongUploadResult=gson.fromJson(uploadResult, YunHeTongUploadImageResult.class);
                if(yunHeTongUploadResult.getCode()!=200){
                    resultModel.setCode(yunHeTongUploadResult.getCode());
                    resultModel.setMessage(yunHeTongUploadResult.getMsg());
                }else{
                    //印章id
                    String moulageId=yunHeTongUploadResult.getData().getMoulageId();
                    param.setFileId(moulageId);
                    magerIndcInfoService.add(param);
                    result.setFileId(moulageId);
                    resultModel.setData(result);//返回上传成功后的访问路径
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                }
            }
            System.out.println("上传结果uploadResult=========="+uploadResult);



        }
        return resultModel;
    }
    /**
    * @Description: 法定代表人的比较特殊，需要单独抽象出来
    * @Param: 分二步，1上传图片，不调用云合同接口，上传图片返回本地路径，等点击认证的时候，在调用接口进行图片上传到云合同
    * @return: java.lang.Object
    * @Author: zhengyunfei
    * @Date: 2019/9/25
    * @time:9:36
    */
    @PostMapping("/api/upload/faren")
    @ResponseBody
    public Object UploadFaRenImage(@RequestParam(value = "file", required = false) MultipartFile file,String operatorId, String type,String caCustId,String token){
        ResultModel resultModel=new ResultModel();
        if(file == null){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }else{
            String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
            String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
            TemplateManagerParam result = writeFile(file, uploadPath, imageDomain);
            TemplateManagerParam param=new TemplateManagerParam();
            //获取前端传递过来的参数
            param.setOperatorId(operatorId);
            param.setType(type);
            if(StringUtil.isNullOrEmpty(caCustId)){
                resultModel.setData(result);//返回上传成功后的访问路径
                resultModel.setCode(ResultStatus.SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                return resultModel;
            }
            param.setCaCustId(caCustId);
            //本地上传完成，再调用云合同上传接口
            System.out.println("token===="+token);
            HttpIOUtil httpReuqest = new HttpIOUtil();
            String uploadResult="";
            Gson gson=new Gson();
            if(MagerIndcInfoContant.TEMPLATE_TYPE_F1.equals(type)||MagerIndcInfoContant.TEMPLATE_TYPE_G1.equals(type)){
                //管理人公章，法定代表人章
                uploadResult=httpReuqest.uploadImageToYunHeTong(token,result.getLocalPath(),caCustId);
                YunHeTongUploadImageResult yunHeTongUploadResult=gson.fromJson(uploadResult, YunHeTongUploadImageResult.class);
                if(yunHeTongUploadResult.getCode()!=200){
                    resultModel.setCode(yunHeTongUploadResult.getCode());
                    resultModel.setMessage(yunHeTongUploadResult.getMsg());
                }else{
                    //印章id
                    String moulageId=yunHeTongUploadResult.getData().getMoulageId();
                    param.setFileId(moulageId);
                    magerIndcInfoService.add(param);
                    result.setFileId(moulageId);
                    resultModel.setData(result);//返回上传成功后的访问路径
                    resultModel.setCode(ResultStatus.SUCCESS.getCode());
                    resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                }
            }
            System.out.println("上传结果uploadResult=========="+uploadResult);



        }
        return resultModel;
    }

    /**
     * @function  单文件上传
     * @return
     */
    public static String fileOne(MultipartFile file, String saveUrl, String imageDomain){
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = IdUtils.getId() + suffix;
        String newUrl = saveUrl+"\\"+ DateUtil.getDays() +"\\"+fileName;
        System.out.println("文件路径：" + newUrl);
        File saveFile = new File(newUrl);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败！";
        }
        return imageDomain+ DateUtil.getDays() +"/"+fileName;
    }
    /**
     * @function  单文件上传
     * @return
     */
    public static TemplateManagerParam writeFile(MultipartFile file, String saveUrl, String imageDomain){
        TemplateManagerParam result=new TemplateManagerParam();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String originName= file.getOriginalFilename();
        //result.setFileName(originName+suffix);//原始文件名+后缀
        result.setOriFileName(originName);//原始文件名+后缀
        String id=IdUtils.getId();
        result.setFileName(id);
        String fileName = id + suffix;
        String newUrl = saveUrl+"/"+ DateUtil.getDays() +"/"+fileName;
        result.setLocalPath(newUrl);
        System.out.println("文件路径：" + newUrl);
        File saveFile = new File(newUrl);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileUrl=imageDomain+ DateUtil.getDays() +"/"+fileName;
        result.setFileUrl(fileUrl);
        return result;
    }


}
